package main

import (
	"github.com/streadway/amqp"
	"log"
	"strconv"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

func fib(n int) int {
	if n == 0 {
		return 0
	} else if n == 1 {
		return 1
	} else {
		return fib(n-1) + fib(n-2)
	}
}
func main() {
	connection, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer connection.Close()

	channel, err := connection.Channel()
	if err != nil {
	}
	defer channel.Close()

	queue, err := channel.QueueDeclare("rpc_queue", false, false, false, false, nil)

	channel.Qos(1, 0, false)

	msgs, err := channel.Consume(queue.Name, "", false, false, false, false, nil)
	forver := make(chan bool)

	go func() {
		for d := range msgs {
			n, _ := strconv.Atoi(string(d.Body))
			log.Printf(" [.] fib(%d)", n)
			response := fib(n)
			log.Printf(" [.] response (%d)", response)
			channel.Publish("",
				d.ReplyTo,
				false,
				false,
				amqp.Publishing{
					ContentType:   "text/plain",
					CorrelationId: d.CorrelationId, Body: []byte(strconv.Itoa(response)),
				})
			d.Ack(false)
		}
	}()
	log.Printf(" [*] Awaiting RPC requests")
	<-forver
}
